<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import {
  getStudentDegreeDataApi,
  getStudentCountDataApi,
} from "@/api/report";

// 学员学历统计
const degreeChartRef = ref();
const degreeChart = ref();
const degreeData = ref([]);

const renderDegreeChart = () => {
  if (!degreeChart.value) {
    degreeChart.value = echarts.init(degreeChartRef.value);
  }
  const option = {
    title: { text: "学员学历分布", left: "center" },
    tooltip: { trigger: "item" },
    legend: { bottom: 10, left: "center" },
    series: [
      {
        name: "学历",
        type: "pie",
        radius: "60%",
        data: degreeData.value,
        emphasis: {
          itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" },
        },
        label: { formatter: "{b}: {c} ({d}%)" },
      },
    ],
  };
  degreeChart.value.setOption(option);
};

// 班级人数统计
const clazzChartRef = ref();
const clazzChart = ref();
const clazzOption = ref({});
const fetchClazzCount = async () => {
  const res = await getStudentCountDataApi();
  if (res.code) {
    // 适配ClazzCountOption结构
    const xAxis = res.data.clazzList || res.data.xAxis || [];
    const series = res.data.dataList || res.data.series || [];
    clazzOption.value = {
      title: { text: "各班级学员人数", left: "center" },
      tooltip: {},
      xAxis: { type: "category", data: xAxis },
      yAxis: { type: "value" },
      series: [
        {
          name: "学员人数",
          type: "bar",
          data: series,
          itemStyle: { color: "#409EFF" },
        },
      ],
    };
    if (!clazzChart.value) {
      clazzChart.value = echarts.init(clazzChartRef.value);
    }
    clazzChart.value.setOption(clazzOption.value);
  }
};

onMounted(async () => {
  // 学历统计
  const res = await getStudentDegreeDataApi();
  if (res.code) {
    degreeData.value = res.data;
    renderDegreeChart();
  }
  // 班级人数统计
  fetchClazzCount();
});
</script>

<template>
  <div>
    <h2>学员信息统计</h2>
    <div style="display: flex; gap: 32px; flex-wrap: wrap;">
      <div style="flex:1; min-width: 400px; height: 400px;">
        <div ref="degreeChartRef" style="width: 100%; height: 100%"></div>
      </div>
      <div style="flex:1; min-width: 400px; height: 400px;">
        <div ref="clazzChartRef" style="width: 100%; height: 100%"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
h2 {
  margin-bottom: 24px;
}
</style>
